<template>
  <div>
    <el-form :inline="true">
      <el-form-item>
        <el-input placeholder="批次号" v-model="searchDto.batch">
          <!--当被选tab为待返还时，才显示返还按钮-->
          <el-button slot="append" @click="batchReturn()" v-if="roleType === '4' && tab === 0">返还
          </el-button>
        </el-input>
      </el-form-item>
      <!--增加返厂人姓名筛选-->
      <el-form-item>
        <el-input placeholder="返厂人姓名" v-model="searchDto.name"></el-input>
      </el-form-item>
      <!--增加YSN筛选功能-->
      <el-form-item>
        <el-input placeholder="YSTSN" v-model="searchDto.ystsn"></el-input>
      </el-form-item>
      <!--增加维修人筛选功能-->
      <el-form-item>
        <el-input placeholder="维修人姓名" v-model="searchDto.repairer"></el-input>
      </el-form-item>
      <!--增加操作人筛选且被选tab为已返还才会存在此input-->
      <el-form-item>
        <el-input placeholder="操作人" v-model="searchDto.operator" v-if="tab === 1"></el-input>
      </el-form-item>
      <!--增加工厂账号待返还界面的维修结果筛选-->
      <el-form-item>
        <el-select clearable placeholder="请选择维修结果" v-model="searchDto.repairResult" v-if="roleType === '4' && tab ===
         0">
          <el-option
            v-for="item in repairResultOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <!--增加省份筛选-->
      <el-form-item>
        <v-distpicker @selected="onSelected" :provinceOut="searchDto.province" only-province>
        </v-distpicker>
      </el-form-item>
      <!--查询时间-->
      <el-form-item>
        <el-date-picker
          v-if="tab === 1"
          v-model="searchDto.returnTime"
          type="daterange"
          value-format="yyyy-MM-dd"
          range-separator="至"
          start-placeholder="返还开始时间"
          end-placeholder="返还结束时间"
          align="right">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="searchDate()">查询</el-button>
      </el-form-item>
      <!--判断被选tab，为待返还时才显示按钮'设备返还'-->
      <el-form-item v-if="roleType === '4'&& tab === 0">
        <el-button type="primary" @click="returnDevice">设备返还</el-button>
      </el-form-item>
      <!--增加待返还数据导出功能-->
      <el-form-item v-if="tab === 0">
        <el-button type="primary" :loading="unExportLoading" @click="excelExport()">数据导出</el-button>
      </el-form-item>
      <!--增加已返还数据导出功能-->
      <el-form-item v-if="tab === 1">
        <el-button type="primary" :loading="finishExportLoading" @click="excelExport1()">数据导出</el-button>
      </el-form-item>
    </el-form>
    <el-tabs type="border-card" v-model="activeName" @tab-click="handleClick(activeName)">
      <el-tab-pane label="待返还" name="unReturn">
        <custom-table
          :multipleSelection="roleType === '4'"
          :data="returnWorkOrderList"
          :columns="columns"
          :tableLoadingFlag="tableLoadingFlag"
          :operationColumn="operationColumn"
          :pagination="pagination"
          @selection-change="selectionChange">
        </custom-table>
      </el-tab-pane>
      <el-tab-pane label="已返还" name="alreadyReturn">
        <custom-table
          :data="returnFinishOrderList"
          :columns="finishColumns"
          :tableLoadingFlag="finishTableLoadingFlag"
          :pagination="pagination1">
        </custom-table>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
  import CustomTable from '@/components/table/CustomTable'
  import {
    apiReturnExport,
    apiGetFactoryReturnList,
    apiGetReturnBatchList,
    apiGetReturnDeviceFinishList,
    apiFinishReturnExport
  } from '@/api/repairs/factory/index'
  import {parseTime} from '@/utils'
  import {getRoleType} from '@/utils/token'
  import {downloadExcel} from "../../../utils";

  export default {
    components: {
      CustomTable
    },
    created () {
      let listQuery = {
        pageNumber: this.pagination.currentPage,
        pageSize: this.pagination.pageSize
      }
      this.apiGetFactoryReturnList(listQuery)
      this.roleType = getRoleType()
      // 不是工厂操作按钮隐藏
      if (this.roleType !== '4') {
        this.operationColumn = null
      }
    },
    data () {
      return {
        // 当前tab
        tab: 0,
        // tab标签页
        activeName: 'unReturn',
        tableLoadingFlag: false,
        columns: [
          {label: 'ID', name: 'id', width: '80', align: 'center'},
          {label: '批次号', name: 'batch', align: 'center'},
          {label: '省份', name: 'province', align: 'center'},
          {label: '地市', name: 'city', align: 'center'},
          {label: '返厂人姓名', name: 'name', align: 'center'},
          {label: '联系电话', name: 'tel', align: 'center'},
          {label: '型号', name: 'model', align: 'center'},
          {label: 'YSTSN', name: 'ystsn', align: 'center', width: '180'},
          {label: '更新后的YSTSN', name: 'updateAfterYstsn', align: 'center', width: '180'},
          {label: '维修工厂', name: 'factoryName', align: 'center'},
          {label: '维修结果', name: 'result', align: 'center'},
          {label: '维修人', name: 'repairer', align: 'center'},
          {label: '维修时间', name: 'repairDate', align: 'center', width: '180'}
        ],
        operationColumn: {
          width: '80',
          operations: [
            {name: '返还', callback: this.onBtnReturn}
          ]
        },
        repairResultOptions: [{
          value: '2',
          label: '已修复'
        }, {
          value: '3',
          label: '原物返还'
        }, {
          value: '5',
          label: '已报废'
        }],
        listQuery: {
          repairResult: undefined,
          ystsn: undefined,
          batch: undefined,
          name: undefined,
          province: undefined,
          operator: undefined,
          returnTime: undefined,
          beginTime: undefined,
          endTime: undefined,
          repairer: undefined
        },
        searchDto: {
          repairResult: '',
          ystsn: '',
          batch: '',
          name: '',
          province: '',
          operator: '',
          returnTime: '',
          beginTime: '',
          endTime: '',
          repairer: ''
        },
        returnWorkOrderList: [],
        pagination: this.getData(this.apiGetFactoryReturnList),
        pagination1: this.getData(this.apiGetReturnDeviceFinishList),
        selectionList: [],
        roleType: getRoleType(),
        finishTableLoadingFlag: false,
        finishColumns: [
          {label: 'ID', name: 'id', width: '80', align: 'center'},
          {label: '批次号', name: 'batch', align: 'center'},
          {label: '省份', name: 'province', align: 'center'},
          {label: '品牌', name: 'brand', align: 'center'},
          {label: '型号', name: 'model', align: 'center'},
          {label: 'YSTSN', name: 'ystsn', align: 'center', width: '180'},
          {label: '更新后的YSTSN', name: 'updateAfterYstsn', align: 'center', width: '180'},
          {label: '返厂人姓名', name: 'backName', align: 'center'},
          {label: '操作人', name: 'operator', align: 'center'},
          {label: '责任归属', name: 'duty', align: 'center'},
          {label: '维修工厂', name: 'factoryName', align: 'center'},
          {label: '维修结果', name: 'repairResult', align: 'center'},
          {label: '维修人', name: 'repairer', align: 'center'},
          {label: '维修时间', name: 'repairDate', align: 'center', width: '180'},
          {label: '返还时间', name: 'backTime', align: 'center', formatter: this.formatTime, width: '180'},
          {label: '物流单号', name: 'logisticsNumber', align: 'center'},
          {label: '物流公司', name: 'logisticsCompany', align: 'center'},
          {label: '状态', name: 'status', align: 'center'},
          {label: '接收人', name: 'pointReceiverName', align: 'center'},
          {label: '接收时间', name: 'pointReceiveTime', align: 'center', formatter: this.formatTime, width: '180'},
          {label: '接收备注', name: 'pointReceiveRemark', align: 'center'}
        ],
        returnFinishOrderList: [],
        unExportLoading: false,
        finishExportLoading: false
      }
    },
    methods: {
      formatTime (row, column, cellValue) {
        return parseTime(cellValue)
      },
      // 按条件查询
      searchDate () {
        this.listQuery.batch = this.searchDto.batch
        this.listQuery.name = this.searchDto.name
        this.listQuery.province = this.searchDto.province
        this.listQuery.operator = this.searchDto.operator
        this.listQuery.ystsn = this.searchDto.ystsn
        this.listQuery.repairer = this.searchDto.repairer
        if (this.tab === 0) {
          this.listQuery.repairResult = this.searchDto.repairResult
          this.tableLoadingFlag = true
          this.pagination.currentPage = 1
          this.pagination.pageSize = 10
          apiGetFactoryReturnList(this.listQuery).then(response => {
            this.returnWorkOrderList = response.data
            this.pagination.totalRecords = response.totalRecords
            this.tableLoadingFlag = false
          }).catch(() => {
            this.tableLoadingFlag = false
          })
        } else if (this.tab === 1) {
          this.listQuery.beginTime = this.searchDto.returnTime === null ? '' : this.searchDto.returnTime[0]
          this.listQuery.endTime = this.searchDto.returnTime === null ? '' : this.searchDto.returnTime[1]
          this.finishTableLoadingFlag = true
          this.pagination1.currentPage = 1
          this.pagination1.pageSize = 10
          apiGetReturnDeviceFinishList(this.listQuery).then(response => {
            this.returnFinishOrderList = response.data
            this.pagination1.totalRecords = response.totalRecords
            this.finishTableLoadingFlag = false
          }).catch(() => {
            this.finishTableLoadingFlag = false
          })
        }
      },
      apiGetFactoryReturnList (listQuery) {
        this.tableLoadingFlag = true
        if (this.listQuery.batch !== undefined) {
          listQuery.batch = this.listQuery.batch
        }
        if (this.listQuery.name !== undefined) {
          listQuery.name = this.listQuery.name
        }
        // 设置listQuery中的province的值
        if (this.listQuery.province !== undefined) {
          listQuery.province = this.listQuery.province
        }
        // 设置listQuery中的ystsn的值
        if (this.listQuery.ystsn !== undefined) {
          listQuery.ystsn = this.listQuery.ystsn
        }
        // 设置listQuery中的repaier的值
        if (this.listQuery.repairer !== undefined) {
          listQuery.repairer = this.listQuery.repairer
        }
        if (this.listQuery.repairResult !== undefined) {
          listQuery.repairResult = this.listQuery.repairResult
        }
        apiGetFactoryReturnList(listQuery).then(response => {
          this.returnWorkOrderList = response.data
          this.pagination.totalRecords = response.totalRecords
          this.tableLoadingFlag = false
        }).catch(() => {
          this.tableLoadingFlag = false
        })
      },
      apiGetReturnDeviceFinishList (listQuery) {
        this.finishTableLoadingFlag = true
        // 设置listQuery中的repairer的值
        if (this.listQuery.repairer !== undefined) {
          listQuery.repairer = this.listQuery.repairer
        }
        // 设置listQuery中的ystsn的值
        if (this.listQuery.ystsn !== undefined) {
          listQuery.ystsn = this.listQuery.ystsn
        }
        if (this.listQuery.batch !== undefined) {
          listQuery.batch = this.listQuery.batch
        }
        if (this.listQuery.name !== undefined) {
          listQuery.name = this.listQuery.name
        }
        if (this.listQuery.province !== undefined) {
          listQuery.province = this.listQuery.province
        }
        if (this.listQuery.operator !== undefined) {
          listQuery.operator = this.listQuery.operator
        }
        if (listQuery.beginTime === undefined) {
          listQuery.beginTime = this.listQuery.beginTime
        }
        if (listQuery.endTime === undefined) {
          listQuery.endTime = this.listQuery.endTime
        }
        apiGetReturnDeviceFinishList(listQuery).then(response => {
          this.returnFinishOrderList = response.data
          this.pagination1.totalRecords = response.totalRecords
          this.finishTableLoadingFlag = false
        }).catch(() => {
          this.finishTableLoadingFlag = false
        })
      },
      // 批量返还
      batchReturn () {
        this.listQuery.batch = this.searchDto.batch
        if (this.listQuery.batch === null || this.listQuery.batch === '') {
          this.$alert('批次号不能为空', '返还失败', {
            confirmButtonText: '确定'
          })
          return
        }
        apiGetReturnBatchList(this.listQuery).then(response => {
          let list = response.data
          if (list.length <= 0) {
            this.$alert('该批次号没有设备返还', '返还失败', {
              confirmButtonText: '确定'
            })
            return
          } else {
            this.$confirm('此操作将返还批次号为：' + this.listQuery.batch + '的维修设备，共' + list.length + '台, 是否继续?', '确认返还', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              // 物流信息录入界面
              this.$router.push({
                path: '/repairs/logistics',
                query: {
                  batch: this.listQuery.batch,
                  ids: list,
                  type: 0,
                  userId: ''
                }
              })
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '已取消返还'
              })
            })
          }
        }).catch(() => {
          this.tableLoadingFlag = false
        })
      },
      onBtnReturn (row) {
        // 物流信息录入界面
        let ids = []
        ids[0] = row.id
        this.$router.push({
          path: '/repairs/logistics',
          query: {
            batch: row.batch,
            ids: ids,
            type: 0,
            userId: row.userId
          }
        })
      },
      onSelected (data) {             // 省市区联动回调
        this.searchDto.province = data.province.code
      },
      selectionChange (val) {
        this.selectionList = val
      },
      handleClick (activeName) {
        if (activeName === 'unReturn') {
          this.tab = 0
          this.searchDate()
        } else if (activeName === 'alreadyReturn') {
          this.tab = 1
          this.searchDate()
        }
      },
      // 数据导出
      excelExport () {
        this.unExportLoading = true
        let paramsPost = {
          batch: this.searchDto.batch,
          name: this.searchDto.name,
          province: this.searchDto.province,
          // 使requestBody中包含ystsn字段，并赋值
          ystsn: this.searchDto.ystsn,
          // 使requestBody中包含repairer字段，并赋值
          repairer: this.searchDto.repairer,
          roleType: getRoleType(),
          repairResult: this.searchDto.repairResult
        }
        apiReturnExport(paramsPost).then(response => {
          downloadExcel(response.data, '自有售后工厂待返还记录信息导出表')
          this.unExportLoading = false
        }).catch(() => {
          this.unExportLoading = false
        })
      },
      excelExport1 () {
        this.finishExportLoading = true
        let paramsPost = {
          batch: this.searchDto.batch,
          name: this.searchDto.name,
          province: this.searchDto.province,
          // 使requestBody中包含ystsn字段，并赋值
          ystsn: this.searchDto.ystsn,
          // 使requestBody中包含repairer字段，并赋值
          repairer: this.searchDto.repairer,
          operator: this.searchDto.operator,
          roleType: getRoleType(),
          beginTime: this.searchDto.returnTime === null ? '' : this.searchDto.returnTime[0],
          endTime: this.searchDto.returnTime === null ? '' : this.searchDto.returnTime[1]
        }
        apiFinishReturnExport(paramsPost).then(response => {
          downloadExcel(response.data, '自有售后工厂已返还记录信息导出表')
          this.finishExportLoading = false
        }).catch(() => {
          this.finishExportLoading = false
        })
      },
      returnDevice () {
        if (this.selectionList === undefined || this.selectionList.length === 0) {
          this.$message({
            showClose: true,
            message: '未选中任何设备',
            type: 'warn'
          })
          return
        }
        let pointId = null
        let pointType = null
        let ids = []
        for (let i in this.selectionList) {
          if (pointId === null) {
            pointId = this.selectionList[i].pointId
          }
          if (pointType === null) {
            pointType = this.selectionList[i].pointType
          }
          // 根据pointId和pointType，对选中的设备进行判断
          if (pointType !== null && pointId !== null) {
            // pointId和pointType同时都相同才可以一起返还同一办事处
            if (pointId === this.selectionList[i].pointId && pointType === this.selectionList[i].pointType) {
              ids.push(this.selectionList[i].id)
            } else {
              // 不相同则弹出提示框，并拒绝此次返还
              this.$alert('所选设备，返还不同办事处，请分开返还', '返还失败', {
                confirmButtonText: '确定'
              })
              return
            }
          }
        }
        this.$confirm('此操作返还设备:' + this.selectionList.length + '台 ' + '确认返还', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 物流信息录入界面
          this.$router.push({
            path: '/repairs/logistics',
            query: {
              batch: '',
              ids: ids,
              type: 1,
              userId: this.selectionList[0].userId
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消返还'
          })
        })
      }
    }
  }
</script>
